<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Services\Tools\CommonService;
use Illuminate\Http\Request;    //引用http请求类
use App\Exceptions\BasicException;  //引入框架异常处理类
use App\Models\MainDB\RechargeRefundRecord;
use App\Response\Response;
use App\Services\Tools\CurlService;
use App\Services\Tools\FinancialService;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController {

    /**
     * @api {post} /order/recharge_list 充值订单列表
     *
     * @apiGroup 订单管理
     *
     * @apiParam {int} pay_type 支付方式
     * @apiParam {string} pay_channel 支付渠道
     * @apiParam {int} pay_status 支付状态：0：不限制（默认）；1：未支付；2：已支付
     * @apiParam {int} user_code 用户编号
     * @apiParam {string} order_sn 订单编号
     * @apiParam {string} trade_no 交易号
     * @apiParam {string} add_time_start 创建时间开始，yyyy-mm-dd
     * @apiParam {string} add_time_end 创建时间结束，yyyy-mm-dd
     * @apiParam {string} pay_time_start 支付时间开始，yyyy-mm-dd
     * @apiParam {string} pay_time_end 支付时间结束，yyyy-mm-dd
     * @apiParam {int} receive_account_id 收款账户id，0（默认）：不限制；其它的根据“获取收款账户列表”接口获取
     * @apiParam {int} page 第几页
     * @apiParam {int} page_size 每页显示条数
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 2122021, 序号
    "user_id": 632524, 用户id
    "order_sn": "20210801480851724926", 订单编号
    "trade_no": "4200001180202108013651359902", 交易号
    "money": "30.00", 充值金额
    "gold": 3000, 获得金币数
    "status": 2, 支付状态：1.待支付 2.已支付
    "type": 5,
    "add_time": "2021-08-01 00:14:45", 创建时间
    "pay_time": "2021-08-01 00:14:58", 支付时间
    "user_code": 786480, 用户编号
    "nickname": "囍你", 昵称
    "pay_type": "H5微信", 支付方式
    "pay_status": "已支付" 支付状态
    "merchant_name": "微信明日" 收款账户名称
    }
    ],
    "first_page_url": "http://local.qipaoadmin/order/recharge_list?page=1",
    "from": 1,
    "last_page": 2121231,
    "last_page_url": "http://local.qipaoadmin/order/recharge_list?page=2121231",
    "next_page_url": "http://local.qipaoadmin/order/recharge_list?page=2",
    "path": "http://local.qipaoadmin/order/recharge_list",
    "per_page": "1",
    "prev_page_url": null,
    "to": 1,
    "total": 2121231
    }
    }
     */
    public function rechargeList(Request $request)
    {
        $param = $request->only('pay_type', 'pay_channel', 'pay_status', 'user_code', 'order_sn', 'trade_no', 'add_time_start', 'add_time_end', 'pay_time_start', 'pay_time_end', 'receive_account_id', 'receive_account_name', 'page', 'page_size', 'refund_status', 'merchant_name');
        //参数校验
        $v = app('validator')->make($param,
            [
                'pay_type' => 'integer|min:0',
                'pay_status' => 'integer|in:0,1,2,3,4,5',
                'user_code' => 'integer',
                'add_time_start' => 'date_format:Y-m-d',
                'add_time_end' => 'date_format:Y-m-d',
                'pay_time_start' => 'date_format:Y-m-d',
                'pay_time_end' => 'date_format:Y-m-d',
                'receive_account_id' => 'integer|min:0',
                'receive_account_name' => 'string',
                'page' => 'integer|min:1',
                'page_size' => 'integer|min:1|max:100',
                'refund_status'=>'integer|min:1|max:100',
                'merchant_name'=>'string',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
        $list = app('repo_user_recharge')->getList($param);

        return  Response::sendData($list);
    }

    /**
     * @api {post} /order/user_recharge_total  用户充值统计
     * @apiVersion 0.1.0
     * @apiName 用户充值统计
     * @apiGroup 订单管理
     * @apiParam {string} start_time     开始时间，非必传
     * @apiParam {string} end_time      结束时间，非必传
     * @apiParam {number} start_amount     开始充值金额，非必传
     * @apiParam {number} end_amount     结束充值金额，非必传
     * @apiParam {number} user_id     用户id，非必传
     * @apiSuccessExample 成功响应
          {
            "code": 200,
            "data": {
                "total_money(累计总的充值金额)": "108.00",
                "alipay(支付宝)": 0,
                "wxpay（微信）": 0,
                "apple_pay（苹果内购）": "24.00",
                "h5_alipay（H5支付宝）": "6.00",
                "h5_wxpay（H5微信）": 0,
                "start_time（搜索开始时间）": "2020-07-23",
                "end_time（搜索结束时间）": "2020-07-24",
                "start_amount（搜索开始金额）": "5",
                "end_amount（搜索结束金额）": "8"
            }
        }
     */
    public  function  userRechargeTotal(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'start_time' => 'filled|date_format:"Y-m-d"',
                'end_time' => 'filled|date_format:"Y-m-d"|after_or_equal:start_time',
                'start_amount' => 'filled|numeric|min:0',
                'end_amount' => 'filled|numeric|min:0|gt:start_amount',
                'user_id' => 'required|numeric|min:1',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $user_id = $request->input('user_id',0);
        $start_time = $request->input('start_time','');
        $end_time = $request->input('end_time','');
        $start_amount = $request->input('start_amount','');
        $end_amount = $request->input('end_amount','');
        $time =  CommonService::transTime($start_time,$end_time);
        $where[]= ['status',2];
        $where[]= ['user_id',$user_id];
        if ($start_amount && !$end_amount){
            $where[]= ['money','>=',$start_amount];
        }
        if (!$start_amount && $end_amount){
            $where[]= ['money','<=',$end_amount];
        }
        if ($start_amount && $end_amount){
            $search_money = [$start_amount,$end_amount];
            $where[]= [function($query) use($search_money){
                $query->whereBetween('money',$search_money);
            }];
        }
        $search_time = [$time['start_at'],$time['end_at']+86400];
        $where[] =[function($query) use ($search_time){
            $query->whereBetween('add_time',$search_time);
        }];
        $total_money = app('repo_user_recharge')->userRechargeTotal($where);
        $result = array_column($total_money, 'total_money', 'type');
        $all_total_money =app('repo_user_recharge')->userAllRechargeTotal($user_id);
        $data = [
            'total_money'=>$all_total_money->total_money ?? 0,
            'alipay'=>$result[1] ?? 0,
            'wxpay'=>$result[2] ?? 0,
            'apple_pay'=>$result[3] ?? 0,
            'h5_alipay'=>$result[4] ?? 0,
            'h5_wxpay'=>$result[5] ?? 0,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'start_amount'=>$start_amount,
            'end_amount'=>$end_amount,
        ];
        return Response::sendData($data);
    }

    /**
     * @api {post} /order/recharge_search_list 充值订单搜索条件列表
     * @apiVersion 0.1.0
     * @apiName 充值订单搜索条件列表
     * @apiGroup 订单管理
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "pay_status_list(支付状态列表)": {
                    "1": "未支付",
                    "2": "已支付"
                },
                "pay_type_list（支付方式列表）": {
                    "1": "支付宝",
                    "2": "微信",
                    "3": "苹果内购",
                    "4": "H5支付宝",
                    "5": "H5微信"
                },
                "channel_list（渠道列表）": [
                    {
                    "channel_no（渠道编号）": "default",
                    "name（渠道名字）": "default"
                    }
                ],
            }
        }
     */
    public  function  rechargeSearchList()
    {
        //支付状态
        $pay_status =[
            '1'=>'未支付',
            '2'=>'已支付',
            '3' => '退款中',
            '4' => '退款成功',
            '5' => '退款失败',
        ];
        //支付方式
        $pay_type =[
            '1'=>'支付宝',
            '2'=>'微信',
            '3'=>'苹果内购',
            '4'=>'H5支付宝',
            '5'=>'H5微信',
        ];
        //渠道
        $channels =app('repo_channel')->channelList([], 0);
        $data = [
            'pay_status_list'=>$pay_status,
            'pay_type_list'=>$pay_type,
            'channel_list'=>$channels,
        ];
        return Response::sendData($data);
    }

    /**
     * @api {get} /order/receive-account 获取收款账户列表
     *
     * @apiGroup 订单管理
     *
     * @apiParam {Int} pay_method 支付方式，0（默认）：不限制；1：支付宝；2：微信；3：苹果内购；4：支付宝h5；5：微信h5
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 1,
    "name": "微信鱼糖"
    },
    {
    "id": 2,
    "name": "微信明日"
    },
    {
    "id": 3,
    "name": "微信氧鱼"
    },
    {
    "id": 4,
    "name": "微信啸南"
    }
    ]
    }
     */
    public function getReceiveAccount(Request $request)
    {
        $param = $request->only('pay_method');
        $v = app('validator')->make($param, [
            'pay_method' => 'integer|in:0,1,2,3,4,5',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $payMethod = $param['pay_method'] ?? 0;

        if ($payMethod == 1 || $payMethod == 4) {
            $merchantType = 1;
        } else if ($payMethod == 2 || $payMethod == 5) {
            $merchantType = 2;
        } else if ($payMethod == 3) {
            $merchantType = 0;
        } else if ($payMethod == 0) {
            $merchantType = -1;
        }

        $where = [];
        if ($merchantType != -1) {
            $where = ['merchant_type' => $merchantType];
        }

        $receiveAccount = app('model_pay_merchant')->select('id', 'name')->where($where)->get();
        return Response::sendData($receiveAccount);
    }

    /**
     * @api {get} /order/pay_recharge_refund_detail 财务-获取充值退款信息详情
     *
     */
    public function payRechargeRefundDetail(Request $request)
    {
        $param = $request->only('order_sn');
        $v = app('validator')->make($param, [
            'order_sn' => 'string|required',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $order_sn = $param['order_sn'] ?? '';

        $data = [
            'order_sn' => $order_sn,
        ];
        $res = (new FinancialService())->payRechargeRefundDetail($data);
        if (is_string($res)) {
            throw new BasicException(0, $res);
        }

        return Response::sendData($res['data']);
    }

    /**
     * @api {post} /order/pay_recharge_refund 财务-充值退款操作
     *
     */
    public function payRechargeRefund(Request $request)
    {
        $param = $request->only('order_sn', 'refund_money', 'operator_name', 'remark');
        $v = app('validator')->make($param, [
            'order_sn' => 'string|required',
            'refund_money' => 'required',
            'operator_name' => 'string|required',
            'remark' => 'string|required',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $data = [
            'order_sn' => $param['order_sn']??'',
            'refund_money' => $param['refund_money'] ?? 0.00,
            'operator_name' => $param['operator_name']??'',
            'remark' => $param['remark'] ?? '',
        ];

        //获取充值详情
        $info = app('model_user_recharge')
        ->where(['order_sn' => $data['order_sn']])
            ->first()->toArray();


        //只有已支付和退款失败才能退款
        if ($info['status']!=2) {
            throw new BasicException(0, '该订单无法进行退款，订单状态并非已支付或退款失败');
        }
        if ($info['status'] == 2 && !in_array($info['refund_status'],[RechargeRefundRecord::REFUND_STATUS_WATI, RechargeRefundRecord::REFUND_STATUS_FAIL])) {
            throw new BasicException(0, '该订单无法进行退款，订单状态并非已支付或退款失败');
        }

        $res = (new FinancialService())->payRechargeRefund($data);
     
        if (is_string($res)) {
            throw new BasicException(0, $res);
        }
        if(isset($res['code']) && $res['code']==200){
            //更改订单状态
            app('model_user_recharge')
            ->where(['order_sn' => $data['order_sn']])
            ->update(['refund_status'=> RechargeRefundRecord::REFUND_STATUS_ING]);

            $refunddata = [
            'order_sn' => $data['order_sn'],
            'refund_money' => $data['refund_money']*100,
            'status' => RechargeRefundRecord::REFUND_STATUS_ING,//待退款
            'operator_name' => $data['operator_name'],
            'remark' => $data['remark'],
            'refund_apply_time'=>date("Y-m-d H:i:s")
            ];
            //添加退款记录
            app('model_recharge_refund_record')->insert($refunddata);
        }

        return Response::sendData($refunddata);
    }

}
